package com.acoffee.controller;

//import com.acoffee.mapper.DeptMapper;
import com.acoffee.mapper.DeptMapper;
import com.acoffee.mapper.EmpMapper;
import com.acoffee.pojo.Dept;
import com.acoffee.pojo.Emp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;

/**
 * @author acoffee
 * @create 2021-09-07 19:49
 */
@Controller
public class EmpController {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    @RequestMapping("/emps")
    public String list(Model model){
        List<Emp> employees = empMapper.queryEmpList();
        for(Emp emp:employees){
            System.out.println(emp);
        }
        model.addAttribute("emps",employees);
        return "emp/list";
    }

    @GetMapping("/emp")
    public String toAddpage(Model model){
        //查出所有部门的信息
        List<Dept> departments = deptMapper.queryDept();
        model.addAttribute("departments",departments);
        return "emp/add";
    }

    @PostMapping("/emp")
    public String addEmp(Emp employee){
        System.out.println("save→"+employee);
        empMapper.addEmp(employee);//调用底层业务方法保存员工信息
        //添加的组件 forward
        return "redirect:/emps";
    }

    //去员工的修改页面
    @GetMapping("/emp/{id}")
    public String toUpdateEmp(@PathVariable("id")Integer id,Model model){
        //查出原来的数据
        Emp employee = empMapper.queryEmpById(id);
        model.addAttribute("emp",employee);
        //查出所有部门的信息
        Collection<Dept> departments = deptMapper.queryDept();
        model.addAttribute("departments",departments);
        return "emp/update";
    }

    @PostMapping("/updateEmp")
    public String updateEmp(Emp employee){
        System.out.println("save→"+employee);
        empMapper.updateEmp(employee);
        return "redirect:/emps";
    }

    //删除员工
    @GetMapping("/delemp/{id}")
    public String deleteEmp(@PathVariable("id")int id){
        empMapper.deleteEmp(id);
        return "redirect:/emps";
    }
}
